import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'home',
    component: () => import('@/views/Home.vue')
  },
  {
    path: '/article',
    name: 'article',
    component: () => import('@/views/Article.vue')
  },
  {
    path: '/detail',
    name: 'detail',
    component: () => import('@/views/Detail.vue')
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/Login.vue')
  }
]
// 全局前置守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('token'); // 假设通过localStorage中的token判断用户是否登录
  const whiteList = ['Login', 'Register']; // 白名单
  if (whiteList.includes(to.name) || isAuthenticated) {
    next(); // 白名单内的路由或者已登录，直接放行
  } else {
    next({ name: 'Login' }); // 未登录且不在白名单内，跳转到登录页
  }
});

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

export default router